/**
 * @file command_executor_core.cpp
 * @brief ESP32沙画机命令执行器核心实现
 * 
 * 核心功能:
 * - 命令互斥保护
 * - 基础状态管理
 * - 通用辅助函数
 * - 构造函数和初始化
 */

#include "command_executor.h" 
#include "command_executor_debug.h"
#include "command_executor_performance.h"
#include "device_state_manager.h"
#include "led_control_center.h"
#include <ArduinoJson.h>
#include <esp_task_wdt.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/semphr.h>

// 🚨 命令互斥保护静态变量定义
bool CommandExecutor::commandInProgress = false;
unsigned long CommandExecutor::lastCommandTime = 0;
String CommandExecutor::lastExecutedCommand = "";

// ==================== 内存优化常量 ====================
static const int JSON_SMALL_BUFFER = 192;      // 基础状态信息（减少64字节）
static const int JSON_MEDIUM_BUFFER = 384;     // 标准JSON响应（减少128字节） 
static const int JSON_LARGE_BUFFER = 768;      // 复杂数据结构（增加256字节以减少重分配）
static const int MAX_DEBUG_OUTPUT_LENGTH = 96; // 调试输出长度（减少32字节）
static const int STRING_RESERVE_SIZE = 64;     // String预分配大小

// ==================== 构造函数 ====================

CommandExecutor::CommandExecutor(
    PatternLoader* loader,
    MotionController* motion,
    WiFiManager* wifi,
    LEDManager* led,
    LEDControlCenter* ledControl,
    DeviceStateManager* stateManager,
    Preferences* prefs,
    bool* sysPowerEnabled,
    bool* drawingActive,
    bool* drawingPaused,
    int* pausedIdx,
    bool* streamMode
) : patternLoader(loader),
    motionController(motion),
    wifiManager(wifi),
    ledManager(led),
    ledControlCenter(ledControl),
    deviceStateManager(stateManager),
    preferences(prefs),
    systemPowerEnabled(sysPowerEnabled),
    isDrawingActive(drawingActive),
    isDrawingPaused(drawingPaused),
    pausedAtIndex(pausedIdx),
    isStreamMode(streamMode),
    networkTaskCallback(nullptr),
    autoPlayCommandCallback(nullptr),
    drawingCompletedTime(0),
    autoPlayWaiting(false),
    motorTaskHandle(NULL),
    motorTaskRunning(false),
    motorMutex(nullptr) {
    
    // 创建电机互斥锁
    motorMutex = xSemaphoreCreateMutex();
    if (motorMutex == nullptr) {
        Serial.println("❌ 电机互斥锁创建失败");
    } else {
        Serial.println("✅ 电机互斥锁创建成功");
    }
}

// ==================== 命令互斥保护函数 ====================

bool CommandExecutor::isCommandAllowed(const String& command) {
    unsigned long currentTime = millis();
    
    // 1. 基础防抖保护（减少到250ms）
    if (currentTime - lastCommandTime < 250) {
        return false;
    }
    
    // 2. 关键命令冲突保护
    if (commandInProgress) {
        // 🔧 修复：在暂停状态下允许某些恢复命令
        if (*isDrawingPaused && (command == "start" || command == "stop" || command == "pause")) {
            DEBUG_PRINTF("[PROTECT] 暂停状态下允许命令: %s\n", command.c_str());
            return true;
        }
        
        // 允许重复的stop/pause命令（用户可能多次点击）
        if (command == "stop" || command == "pause") {
            DEBUG_PRINTF("[PROTECT] 允许重复的停止/暂停命令: %s\n", command.c_str());
            return true;
        }
        
        // 其他情况下的命令冲突保护
        if (command == "start" || command == "home") {
            DEBUG_PRINTF("[PROTECT] 命令冲突: %s\n", command.c_str());
            return false;
        }
    }
    
    // 3. 绘图状态保护（仅关键命令）
    if (*isDrawingActive && (command == "home" || command.startsWith("sweep"))) {
        return false;
    }
    
    return true;
}

void CommandExecutor::markCommandStart(const String& command) {
    commandInProgress = true;
    lastCommandTime = millis();
    lastExecutedCommand = command;
    DEBUG_PRINTF("[PROTECT] 命令开始: %s\n", command.c_str());
}

void CommandExecutor::markCommandEnd() {
    commandInProgress = false;
    DEBUG_PRINTF("[PROTECT] 命令完成: %s\n", lastExecutedCommand.c_str());
}

bool CommandExecutor::isSystemBusy() const {
    return commandInProgress || *isDrawingActive;
}

// ==================== 辅助函数 ====================

// 统一系统状态验证函数
bool CommandExecutor::validateSystemState() {
    return *systemPowerEnabled && motionController;
}

// 统一错误处理函数
void CommandExecutor::handleError(int errorCode, const char* context) {
    const char* errorMsg = getErrorDescription(errorCode).c_str();
    Serial.printf("[ERROR] %s: %s\n", context, errorMsg);
    
    // 根据错误代码决定是否进入紧急状态
    if (errorCode >= 2) {  // 系统级错误
        setEmergencyState(String(context) + ": " + errorMsg);
    }
}

// 统一的命令前置检查
bool CommandExecutor::preExecuteCheck(const String& command) {
    if (!validateSystemState()) {
        if (!*systemPowerEnabled) {
            Serial.println(GET_MSG_SYSTEM_SLEEP());
        } else {
            Serial.println("[ERROR] MotionController未初始化");
        }
        return false;
    }
    
    if (!isCommandAllowed(command)) {
        DEBUG_PRINTF("[REJECT] 命令被拒绝: %s\n", command.c_str());
        return false;
    }
    
    markCommandStart(command);
    return true;
}

// 统一的命令后置处理
void CommandExecutor::postExecuteProcess(const String& command, int result) {
    markCommandEnd();
    
    if (result != 0) {
        handleError(result, command.c_str());
    } else {
        DEBUG_PRINTF("[SUCCESS] 命令完成: %s\n", command.c_str());
    }
}

bool CommandExecutor::canExecuteMotorCommand(const String& commandName) {
    return validateSystemState();
}

bool CommandExecutor::quickSystemCheck(const String& operation) {
    if (!*systemPowerEnabled) {
        DEBUG_PRINTF("[ERROR] %s失败: 系统休眠\n", operation.c_str());
        return false;
    }
    
    if (!motionController) {
        DEBUG_PRINTF("[ERROR] %s失败: 控制器未初始化\n", operation.c_str());
        return false;
    }
    
    return true;
}

bool CommandExecutor::quickPatternCheck() {
    if (!patternLoader || !patternLoader->hasMorePoints()) {
        DEBUG_PRINT("[ERROR] 无有效图案数据");
        return false;
    }
    return true;
}

// 统一的图案验证和加载函数（流式模式专用）
int CommandExecutor::validateAndEnsurePattern() {
    Serial.println("[VALIDATE] 开始流式模式图案验证");
    
    if (!patternLoader) {
        Serial.println("[ERROR] 图案加载器未初始化");
        handleError(2, "图案加载器未初始化");
        return 2;
    }
    
    // 检查是否有更多点可用
    bool hasValidPattern = patternLoader->hasMorePoints();
    int estimatedPoints = patternLoader->getTotalEstimatedPoints();
    Serial.printf("[VALIDATE] 有更多点: %s, 预估点数: %d\n", 
                  hasValidPattern ? "是" : "否", estimatedPoints);
    
    if (!hasValidPattern) {
        Serial.println("[VALIDATE] 图案数据无效，尝试加载默认图案");
        int loadResult = loadDefaultOrLastPattern();
        if (loadResult != 0) {
            Serial.printf("[ERROR] 无法加载图案数据，错误码: %d\n", loadResult);
            handleError(2, "无法加载图案数据");
            return 2;
        }
        
        // 重新检查加载后的图案
        hasValidPattern = patternLoader->hasMorePoints();
        Serial.printf("[VALIDATE] 默认图案加载后，有更多点: %s\n", 
                      hasValidPattern ? "是" : "否");
        
        if (!hasValidPattern) {
            Serial.println("[ERROR] 加载默认图案后仍无有效数据");
            handleError(2, "无法获取有效图案数据");
            return 2;
        }
    }
    
    Serial.println("[VALIDATE] 流式模式图案验证完成");
    return 0;
}

// 统一的绘图前准备检查
int CommandExecutor::prepareForDrawing(const String& command) {
    Serial.printf("[PREPARE] 开始绘图前准备检查，命令: %s\n", command.c_str());
    
    // 1. 系统状态检查
    Serial.println("[PREPARE] 执行系统状态检查...");
    if (!preExecuteCheck(command)) {
        Serial.println("[ERROR] 系统状态检查失败");
        return 1;
    }
    Serial.println("[PREPARE] 系统状态检查通过");
    
    // 2. 图案数据检查
    Serial.println("[PREPARE] 执行图案数据检查...");
    int patternResult = validateAndEnsurePattern();
    if (patternResult != 0) {
        Serial.printf("[ERROR] 图案数据检查失败，错误码: %d\n", patternResult);
        postExecuteProcess(command, patternResult);
        return patternResult;
    }
    Serial.println("[PREPARE] 图案数据检查通过");
    
    Serial.println("[PREPARE] 绘图前准备检查全部通过");
    return 0;
}

// ==================== 状态管理函数 ====================

void CommandExecutor::setHomingState() {
    transitionToState(STATE_HOMING, LED_HOMING, "开始归零", false, false);
}

void CommandExecutor::setIdleStateAndEndLED(bool endDrawingSession) {
    if (endDrawingSession) {
        transitionToState(STATE_IDLE, LED_IDLE, "返回空闲状态", true, false);
    } else {
        transitionToState(STATE_IDLE, LED_IDLE, "返回空闲状态", false, false);
    }
}

void CommandExecutor::setDrawingStateAndStartLED() {
    transitionToState(STATE_DRAWING, LED_DRAWING, "开始绘图", true, true);
}

void CommandExecutor::setMaintenanceStateAndStartLED() {
    transitionToState(STATE_MAINTENANCE, LED_DRAWING, "进入维护状态", true, true);
}

void CommandExecutor::setMaintenanceStateOnly() {
    transitionToState(STATE_MAINTENANCE, LED_IDLE, "进入维护状态（仅状态）", false, false);
}

void CommandExecutor::setPausedState() {
    if (ledControlCenter) {
        ledControlCenter->requestStatusChange(LED_PAUSED, "绘图暂停");
        Serial.println("⏸️ LED状态切换为暂停，系统状态保持不变");
    }
    
    if (autoResumeConfig.enabled) {
        startAutoResumeWait();
    }
}

void CommandExecutor::setEmergencyState(const String& reason) {
    transitionToState(STATE_EMERGENCY, LED_EMERGENCY, reason, true, false);
    
    if (motionController) {
        motionController->stop();
        motionController->disableMotors();
    }
    
    *isDrawingActive = false;
    *isDrawingPaused = false;
    *pausedAtIndex = -1;
    
    Serial.printf("🚨 进入紧急状态: %s\n", reason.c_str());
}

void CommandExecutor::transitionToState(SystemState targetSystemState, 
                                       LEDStatus targetLEDStatus, 
                                       const String& reason,
                                       bool manageLEDSession,
                                       bool startSession) {
    if (deviceStateManager) {
        SystemState currentState = deviceStateManager->getSystemState();
        if (currentState != targetSystemState) {
            deviceStateManager->setSystemState(targetSystemState, reason);
            DEBUG_PRINTF("🔄 状态转换: %s -> %s (%s)\n", 
                         getSystemStateString(currentState).c_str(),
                         getSystemStateString(targetSystemState).c_str(),
                         reason.c_str());
        }
    }
    
    if (manageLEDSession && ledControlCenter) {
        if (startSession) {
            if (ledControlCenter->getCurrentStatus() != LED_DRAWING && 
                ledControlCenter->getCurrentStatus() != LED_PAUSED) {
                ledControlCenter->startDrawingSession();
                DEBUG_PRINT("🎨 LED绘图会话已启动");
            }
        } else {
            if (ledControlCenter->getCurrentStatus() == LED_DRAWING || 
                ledControlCenter->getCurrentStatus() == LED_PAUSED) {
                ledControlCenter->endDrawingSession();
                DEBUG_PRINT("🔚 LED绘图会话已结束");
            }
        }
    }
    
    if (ledControlCenter) {
        ledControlCenter->requestStatusChange(targetLEDStatus, reason);
        DEBUG_PRINTF("💡 LED状态转换: %s\n", reason.c_str());
    }
}

// 使用PROGMEM存储常量字符串，节省RAM
static const char STATE_IDLE_STR[] PROGMEM = "空闲";
static const char STATE_HOMING_STR[] PROGMEM = "归零中";
static const char STATE_DRAWING_STR[] PROGMEM = "绘图中";
static const char STATE_EMERGENCY_STR[] PROGMEM = "紧急停止";
static const char STATE_MAINTENANCE_STR[] PROGMEM = "维护中";
static const char STATE_UNKNOWN_STR[] PROGMEM = "未知";

String CommandExecutor::getSystemStateString(SystemState state) {
    switch (state) {
        case STATE_IDLE: return FPSTR(STATE_IDLE_STR);
        case STATE_HOMING: return FPSTR(STATE_HOMING_STR);
        case STATE_DRAWING: return FPSTR(STATE_DRAWING_STR);
        case STATE_EMERGENCY: return FPSTR(STATE_EMERGENCY_STR);
        case STATE_MAINTENANCE: return FPSTR(STATE_MAINTENANCE_STR);
        default: return FPSTR(STATE_UNKNOWN_STR);
    }
}

// ==================== 通用辅助函数 ====================

DynamicJsonDocument CommandExecutor::createOptimizedJsonDoc(int size) {
    // 智能选择缓冲区大小，避免内存浪费
    int optimizedSize;
    if (size <= 0) {
        optimizedSize = JSON_MEDIUM_BUFFER;  // 默认中等大小
    } else if (size <= 200) {
        optimizedSize = JSON_SMALL_BUFFER;   // 小数据使用小缓冲区
    } else if (size <= 400) {
        optimizedSize = JSON_MEDIUM_BUFFER;  // 中等数据
    } else {
        optimizedSize = JSON_LARGE_BUFFER;   // 大数据使用大缓冲区
    }
    return DynamicJsonDocument(optimizedSize);
}

void CommandExecutor::setNetworkTaskCallback(void (*callback)()) {
    networkTaskCallback = callback;
}

// 错误描述常量字符串存储在PROGMEM中
static const char ERROR_SUCCESS_STR[] PROGMEM = "成功";
static const char ERROR_SYSTEM_STR[] PROGMEM = "系统错误";
static const char ERROR_NO_PATTERN_STR[] PROGMEM = "无图案数据";
static const char ERROR_SD_CARD_STR[] PROGMEM = "SD卡错误";
static const char ERROR_UNKNOWN_STR[] PROGMEM = "未知错误";

String CommandExecutor::getErrorDescription(int errorCode) {
    switch (errorCode) {
        case 0: return FPSTR(ERROR_SUCCESS_STR);
        case 1: return FPSTR(ERROR_SYSTEM_STR);
        case 2: return FPSTR(ERROR_NO_PATTERN_STR);
        case 3: return FPSTR(ERROR_SD_CARD_STR);
        default: return FPSTR(ERROR_UNKNOWN_STR);
    }
}

// ==================== 高性能命令解析器 ====================

// 静态命令映射表，存储在PROGMEM中节省RAM
static const CommandMap PROGMEM commandTable[] = {
    {"start", CMD_START, 5},
    {"stop", CMD_STOP, 4},
    {"pause", CMD_PAUSE, 5},
    {"home", CMD_HOME, 4},
    {"sweep", CMD_SWEEP, 5},
    {"sweepprep", CMD_SWEEPPREP, 9},
    {"sweepprev", CMD_SWEEPPREV, 9},
    {"sweepnext", CMD_SWEEPNEXT, 9},
    {"next", CMD_NEXT, 4},
    {"prev", CMD_PREV, 4},
    {"list", CMD_LIST, 4},
    {"status", CMD_STATUS, 6},
    {"info", CMD_INFO, 4},
    {"taskinfo", CMD_TASKINFO, 8},
    {"coreinfo", CMD_COREINFO, 8},
    {"position", CMD_POSITION, 8},
    {"help", CMD_HELP, 4},
    {"enable", CMD_ENABLE, 6},
    {"disable", CMD_DISABLE, 7},
    {"ledon", CMD_LEDON, 5},
    {"ledoff", CMD_LEDOFF, 6},
    {nullptr, CMD_UNKNOWN, 0}  // 终止标记
};

// 缓存上一次解析结果，避免重复解析
static struct {
    String lastCommand;
    CommandType lastType;
    unsigned long timestamp;
} commandCache = {"", CMD_UNKNOWN, 0};

CommandType CommandExecutor::parseCommandFast(const String& command) {
    unsigned long currentTime = millis();
    
    // 检查缓存（针对连续相同命令的优化）
    if (commandCache.lastCommand == command && 
        (currentTime - commandCache.timestamp) < PerformanceConfig::COMMAND_CACHE_TIMEOUT_MS) {
        return commandCache.lastType;
    }
    
    // 预处理：转换为小写并trim（就地操作）
    String cmd = command;
    cmd.trim();
    cmd.toLowerCase();
    
    // 长度预检查
    if (cmd.length() == 0) {
        return CMD_UNKNOWN;
    }
    
    // 查找命令映射表
    const CommandMap* entry = commandTable;
    while (entry->command != nullptr) {
        // 先检查长度，再进行字符串比较
        if (cmd.length() >= entry->minLength) {
            if (FAST_STRING_COMPARE(cmd.c_str(), entry->command, strlen(entry->command))) {
                // 更新缓存
                commandCache.lastCommand = command;
                commandCache.lastType = entry->type;
                commandCache.timestamp = currentTime;
                
                return entry->type;
            }
        }
        entry++;
    }
    
    return CMD_UNKNOWN;
}

// 批量处理执行函数
int CommandExecutor::executeBatchCommands(const String commands[], size_t count) {
    int totalResult = 0;
    
    // 预分配结果数组
    static int results[10];  // 最多批量处理10个命令
    size_t maxBatch = min(count, sizeof(results)/sizeof(results[0]));
    
    for (size_t i = 0; i < maxBatch; i++) {
        CommandType cmdType = parseCommandFast(commands[i]);
        results[i] = executeCommandByType(cmdType);
        
        if (results[i] != 0) {
            totalResult = results[i];  // 记录第一个错误
            if (results[i] >= 2) {  // 严重错误，立即停止批量处理
                break;
            }
        }
    }
    
    return totalResult;
}
